package outputviewer;

import guiobjects.IPaintedObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import user.data.Data;

public class SVGScreenshot extends Thread
{
	private ArrayList<ArrayList<ArrayList<IPaintedObject>>> myGUIObjects;
	private int[] myRelativeWidths;
	private int myFrame;
	
	public SVGScreenshot(ArrayList<ArrayList<ArrayList<IPaintedObject>>> guiObjects, int[] widths, int frame)
	{
		myGUIObjects = guiObjects;
		myRelativeWidths = widths;
		myFrame = frame;
	}
	public void run()
	{
		File f = new File(Data.screenDirectory);
		if (!f.exists())
			f.mkdir();
		int screenNum = 0;
		do
		{
			f = new File(Data.screenDirectory + "/" + Data.screenPrefix + screenNum + ".svg");
			screenNum++;
		} while (f.exists());
		
		System.out.println("Writing SVG image to file: " + f.getAbsolutePath());

        Writer output = null;
        try
        {
	        output = new BufferedWriter(new FileWriter(f));
	        output.flush();
	        
	        output.write("<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG" + 
	        		" 1.1//EN\"\n\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n\n<svg width=\"100%\" "
	        		+ " height=\"100%\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n");
	        
	        int offset = 0;
	        int total = 0;
	        for (int i = 0; i < myRelativeWidths.length; i++)
	        	total += myRelativeWidths[i];
	        
	        for (int i = 0; i < myGUIObjects.size(); i++)
	        {
	        	ArrayList<IPaintedObject> currentFrame = myGUIObjects.get(i).get(0);
	        	for (int j = 0; j < currentFrame.size(); j++)
	        		output.write(currentFrame.get(j).getSVGData(myRelativeWidths[i], offset, total) + "\n");
	        	
	        	currentFrame = myGUIObjects.get(i).get(myFrame);
	        	for (int j = 0; j < currentFrame.size(); j++)
	        		output.write(currentFrame.get(j).getSVGData(myRelativeWidths[i], offset, total) + "\n");
	        	
	        	offset += myRelativeWidths[i];
	        }
	        
	        output.write("</svg>");
	        output.close();
	        System.out.println("Done writing image.");
        }
        catch (IOException e)
        {
        	System.out.println("Error writing screenshot to file.");
        	e.printStackTrace();
        }
		
	}
}
